<template>
  <div class="task-detail-container">
    <el-form
      :model="taskConfigForm"
      :label-position="'top'"
      class="task-detail-form"
    >
      <el-form-item label="执行对象:">
        <el-select
          v-model="taskConfigForm.executeUser"
          placeholder="请选择"
          clearable
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="opt in executeUserOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务名称:">
        <el-select
          v-model="taskConfigForm.taskName"
          placeholder="请选择"
          clearable
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="opt in taskNameOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务区域:">
        <el-select
          v-model="taskConfigForm.taskArea"
          placeholder="请选择"
          multiple
          collapse-tags
          collapse-tags-tooltip
          clearable
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="opt in taskAreaOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
            checkbox
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务类型:">
        <el-radio-group v-model="taskConfigForm.taskType">
          <el-radio
            v-for="option in taskTypeOptions"
            :key="option.value"
            :label="option.value"
          >
            {{ option.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <div class="task-type-content">
        <el-form-item label="任务开始日期:">
          <el-date-picker
            v-model="taskConfigForm.startDate"
            type="date"
            placeholder="请选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <div class="frequency-swapper">
          <div class="frequency-content">
            <el-form-item label="推送频率:">
              <el-select
                v-model="taskConfigForm.frequency"
                placeholder="请选择"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="opt in frequencyOptions"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>

              <el-select
                v-model="taskConfigForm.checkedWeeks"
                multiple
                placeholder="请选择"
                collapse-tags
                clearable
                @visible-change="visible = $event"
              >
                <!-- 顶部全选 -->
                <div class="select-header" @click.stop>
                  <el-checkbox
                    v-model="checkAll"
                    :indeterminate="indeterminate"
                    @change="toggleAll"
                  >
                    全选
                  </el-checkbox>
                </div>

                <!-- 自定义列表 -->
                <el-option
                  v-for="item in weeks"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  class="multi-option"
                  @click.stop
                >
                  <el-checkbox
                    :model-value="
                      taskConfigForm.checkedWeeks.includes(item.value)
                    "
                    @change="(checked: boolean) => toggleItem(item.value, checked)"
                  >
                    {{ item.label }}
                  </el-checkbox>
                </el-option>
              </el-select>
              <MonthCheckboxSelect
                v-model="days"
                placeholder="请选择当月日期"
                :show-count="3"
              />
            </el-form-item>
          </div>
          <!-- <div
            class="week-checkbox-content"
            v-if="taskConfigForm.frequency == 'week'"
          >
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              v-model="taskConfigForm.checkedWeeks"
              @change="handleCheckedWeeksChange"
            >
              <el-checkbox
                v-for="week in weeks"
                :key="week.value"
                :label="week.label"
              >
                {{ week.label }}
              </el-checkbox>
            </el-checkbox-group>
          </div> -->
        </div>
        <el-form-item label="建议完成时间:" class="finished-date">
          <div
            style="
              display: flex;
              flex-direction: column;
              justify-content: flex-start;
            "
          >
            <el-radio-group v-model="taskConfigForm.dateType">
              <el-radio
                v-for="option in dateTypeOptions"
                :key="option.value"
                :label="option.value"
              >
                {{ option.label }}
              </el-radio>
            </el-radio-group>
            <div style="display: flex; justify-content: space-between">
              <el-time-select
                v-model="taskConfigForm.startDate"
                style="width: 150px"
                placeholder="Start time"
                start="08:30"
                step="00:15"
                end="18:30"
              />
              <el-time-select
                v-model="taskConfigForm.startDate"
                style="width: 150px"
                placeholder="End time"
                start="08:30"
                step="00:15"
                end="18:30"
              />
            </div>
          </div>
        </el-form-item>
      </div>
      <el-form-item label="录入说明">
        <el-input
          type="textarea"
          v-model="taskConfigForm.entryRequirements"
          :rows="4"
          placeholder="请输入"
          style="width: 100%"
        ></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary">确认</el-button>
        <el-button plain>取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import type { TaskItem } from "./types";
import MonthCheckboxSelect from "@/components/MonthCheckboxSelect .vue";

const days = ref<string[]>(["2025-09-18"]); // 默认已选

const visible = ref(false);

interface Props {
  detailData: any;
}

// 任务表单数据
const taskForm = reactive({
  id: "",
  taskName: "",
  taskType: "once",
  startTime: "",
  endTime: "",
  region: "",
  taskStatus: "1", // 默认待下发状态
  description: "",
});
const props = defineProps<Props>();
// watch(
//   () => props.detailData,
//   (val) => Object.assign(taskForm, val),
//   { immediate: true }
// );

const router = useRouter();

// 执行对象选项数组，用于动态循环渲染
const executeUserOptions = [
  { label: "张三", value: "0" },
  { label: "李四", value: "1" },
  { label: "王五", value: "2" },
];
// 任务名称选项数组，用于动态循环渲染
const taskNameOptions = [
  { label: "灌溉操作", value: "0" },
  { label: "漏水", value: "1" },
  { label: "录音", value: "2" },
];
// 任务区域选项数组，用于动态循环渲染
const taskAreaOptions = [
  { label: "46号棚", value: "0" },
  { label: "47号棚", value: "1" },
  { label: "48号棚", value: "2" },
  { label: "2号棚", value: "3" },
];
// 任务类型选项数组，用于动态循环渲染
const taskTypeOptions = [
  { label: "单次任务", value: "single" },
  { label: "周期任务", value: "periodic" },
];
// 建议完成时间选项数组，用于动态循环渲染
const dateTypeOptions = [
  { label: "固定时段", value: "0" },
  { label: "立即完成", value: "1" },
];
// 推送频率选项数组，用于动态循环渲染
const frequencyOptions = [
  { label: "每日", value: "day" },
  { label: "每周", value: "week" },
  { label: "每月", value: "month" },
];
const weeks = [
  { label: "周一", value: "week1" },
  { label: "周二", value: "week2" },
  { label: "周三", value: "week3" },
  { label: "周四", value: "week4" },
  { label: "周五", value: "week5" },
  { label: "周六", value: "week6" },
  { label: "周日", value: "week7" },
];
// const checkAll = ref(false);
const isIndeterminate = ref(true);
// 定义任务配置表单的接口类型
export interface TaskConfigForm {
  executeUser: string;
  taskName: string;
  taskArea: string[];
  taskType: string;
  startDate: string;
  frequency: string;
  checkedWeeks: string[];
  dateType: string;
  finishedDate: string;
  entryRequirements: string;
}

// 使用接口类型创建响应式表单对象
const taskConfigForm = reactive<TaskConfigForm>({
  executeUser: "",
  taskName: "",
  taskArea: [],
  taskType: "single",
  startDate: "",
  frequency: "",
  checkedWeeks: [],
  dateType: "0",
  finishedDate: "",
  entryRequirements: "",
});
function goBack() {}
function handleSubmit() {
  console.log(taskConfigForm, "-----taskConfigForm-----");
}
function handleCheckAllChange(value: boolean) {
  if (value) {
    // 全选：将所有星期的label添加到checkedWeeks数组
    taskConfigForm.checkedWeeks = weeks.map((item) => item.label);
  } else {
    // 取消全选：清空checkedWeeks数组
    taskConfigForm.checkedWeeks = [];
  }
  // 更新不确定状态
  isIndeterminate.value = false;
}

/* 全选逻辑 */
const checkAll = computed({
  get: () => taskConfigForm.checkedWeeks.length === weeks.length,
  set: (val: boolean) => toggleAll(val),
});
const indeterminate = computed(
  () =>
    taskConfigForm.checkedWeeks.length > 0 &&
    taskConfigForm.checkedWeeks.length < weeks.length
);

function toggleAll(checked: boolean) {
  taskConfigForm.checkedWeeks = checked ? weeks.map((i) => i.value) : [];
}

function toggleItem(val: any, checked: boolean) {
  const set = new Set(taskConfigForm.checkedWeeks);
  checked ? set.add(val) : set.delete(val);
  taskConfigForm.checkedWeeks = Array.from(set);
}
function handleCheckedWeeksChange(value: string[]) {
  // 检查是否所有星期都被选中
  const checkedCount = value.length;
  const totalCount = weeks.length;

  // 全部选中
  if (checkedCount === totalCount) {
    checkAll.value = true;
    isIndeterminate.value = false;
  }
  // 部分选中
  else if (checkedCount > 0 && checkedCount < totalCount) {
    checkAll.value = false;
    isIndeterminate.value = true;
  }
  // 全部未选中
  else {
    checkAll.value = false;
    isIndeterminate.value = false;
  }
}
</script>

<style lang="scss" scoped>
.task-detail-container {
}
</style>
